package algotithm.leetcode.presum.test525;

import java.util.HashMap;

/**
 * @author 25068
 * @Date 2021/6/3 12:23
 * @Title 525. 连续数组
 */
public class Solution {

    public static void main(String[] args) {
        int[] nums = {1,1,1,1,1,1,1,1};
        Solution solution = new Solution();
        int maxLength = solution.findMaxLength(nums);
        System.out.println(maxLength);
    }

    public int findMaxLength(int[] nums) {
        int n = nums.length;
        HashMap<Integer,Integer> map = new HashMap<>(1024);
        map.put(0, -1);
        int max = 0;
        int zero = 0;
        int one = 0;
        int pre = 0;
        for (int i = 0; i < n; i++) {
            if (nums[i] == 1) {
                one++;
            } else {
                zero++;
            }
            int dis = one - zero;
            if (map.containsKey(dis)) {
                pre = map.get(dis);
                max = Math.max(max,i - pre);
            } else {
                map.put(dis,i);
            }
        }
        return max;
    }
}
